package com.offcn.sellergoods.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.offcn.entity.PageResult;
import com.offcn.sellergoods.dao.*;
import com.offcn.sellergoods.group.GoodsEntity;
import com.offcn.sellergoods.pojo.*;
import com.offcn.sellergoods.service.GoodsService;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/****
 * @Author:ujiuye
 * @Description:Goods业务层接口实现类
 * @Date 2021/2/1 14:19
 *****/
@Service
@Transactional
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private GoodsDescMapper goodsDescMapper;
    @Resource
    private ItemMapper itemMapper;
    @Resource
    private ItemCatMapper itemCatMapper;
    @Resource
    private BrandMapper brandMapper;

    /**
     * Goods条件+分页查询
     *
     * @param goods 查询条件
     * @param page  页码
     * @param size  页大小
     * @return 分页结果
     */
    @Override
    public PageResult<Goods> findPage(Goods goods, int page, int size) {
        Page<Goods> mypage = new Page<>(page, size);
        QueryWrapper<Goods> queryWrapper = this.createQueryWrapper(goods);
        IPage<Goods> iPage = this.page(mypage, queryWrapper);
        return new PageResult<Goods>(iPage.getTotal(), iPage.getRecords());
    }

    /**
     * Goods分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageResult<Goods> findPage(int page, int size) {
        Page<Goods> mypage = new Page<>(page, size);
        IPage<Goods> iPage = this.page(mypage, new QueryWrapper<Goods>());

        return new PageResult<Goods>(iPage.getTotal(), iPage.getRecords());
    }

    /**
     * Goods条件查询
     *
     * @param goods
     * @return
     */
    @Override
    public List<Goods> findList(Goods goods) {
        //构建查询条件
        QueryWrapper<Goods> queryWrapper = this.createQueryWrapper(goods);
        //根据构建的条件查询数据
        return this.list(queryWrapper);
    }


    /**
     * Goods构建查询对象
     *
     * @param goods
     * @return
     */
    public QueryWrapper<Goods> createQueryWrapper(Goods goods) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if (goods != null) {
            // 主键
            if (!StringUtils.isEmpty(goods.getId())) {
                queryWrapper.eq("id", goods.getId());
            }
            // 商家ID
            if (!StringUtils.isEmpty(goods.getSellerId())) {
                queryWrapper.eq("seller_id", goods.getSellerId());
            }
            // SPU名
            if (!StringUtils.isEmpty(goods.getGoodsName())) {
                queryWrapper.eq("goods_name", goods.getGoodsName());
            }
            // 默认SKU
            if (!StringUtils.isEmpty(goods.getDefaultItemId())) {
                queryWrapper.eq("default_item_id", goods.getDefaultItemId());
            }
            // 状态
            if (!StringUtils.isEmpty(goods.getAuditStatus())) {
                queryWrapper.eq("audit_status", goods.getAuditStatus());
            }
            // 是否上架
            if (!StringUtils.isEmpty(goods.getIsMarketable())) {
                queryWrapper.eq("is_marketable", goods.getIsMarketable());
            }
            // 品牌
            if (!StringUtils.isEmpty(goods.getBrandId())) {
                queryWrapper.eq("brand_id", goods.getBrandId());
            }
            // 副标题
            if (!StringUtils.isEmpty(goods.getCaption())) {
                queryWrapper.eq("caption", goods.getCaption());
            }
            // 一级类目
            if (!StringUtils.isEmpty(goods.getCategory1Id())) {
                queryWrapper.eq("category1_id", goods.getCategory1Id());
            }
            // 二级类目
            if (!StringUtils.isEmpty(goods.getCategory2Id())) {
                queryWrapper.eq("category2_id", goods.getCategory2Id());
            }
            // 三级类目
            if (!StringUtils.isEmpty(goods.getCategory3Id())) {
                queryWrapper.eq("category3_id", goods.getCategory3Id());
            }
            // 小图
            if (!StringUtils.isEmpty(goods.getSmallPic())) {
                queryWrapper.eq("small_pic", goods.getSmallPic());
            }
            // 商城价
            if (!StringUtils.isEmpty(goods.getPrice())) {
                queryWrapper.eq("price", goods.getPrice());
            }
            // 分类模板ID
            if (!StringUtils.isEmpty(goods.getTypeTemplateId())) {
                queryWrapper.eq("type_template_id", goods.getTypeTemplateId());
            }
            // 是否启用规格
            if (!StringUtils.isEmpty(goods.getIsEnableSpec())) {
                queryWrapper.eq("is_enable_spec", goods.getIsEnableSpec());
            }
            // 是否删除
            if (!StringUtils.isEmpty(goods.getIsDelete())) {
                queryWrapper.eq("is_delete", goods.getIsDelete());
            }
        }
        return queryWrapper;
    }

    /**
     * 逻辑删除
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        //1.查询
        Goods goods = goodsMapper.selectById(id);
        if (goods.getIsMarketable() != null && "1".equals(goods.getIsMarketable())) {
            throw new RuntimeException("请先下架再删除");
        }
        goods.setIsDelete("1");
        goods.setAuditStatus("0");
        goodsMapper.updateById(goods);
    }

    /**
     * 修改Goods
     *
     * @param goodsEntity
     */
    @Override
    public void update(GoodsEntity goodsEntity) {
        //修改未审核
        Goods goods = goodsEntity.getGoods();
        goods.setAuditStatus("0");
        //1.sku
        goodsMapper.updateById(goods);
        //2.desc
        goodsDescMapper.updateById(goodsEntity.getGoodsDesc());
        //3.先删除再修改
        QueryWrapper<Item> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id", goods.getId());
        itemMapper.delete(wrapper);
        //4.添加
        this.saveItemList(goodsEntity);
    }


    /**
     * 增加Goods
     *
     * @param goodsEntity
     */
    @Override
    public void add(GoodsEntity goodsEntity) {
        //1.获取商品对象
        Goods goods = goodsEntity.getGoods();
        //1.1设置审核状态
        goods.setAuditStatus("0");
        //保存商品
        goodsMapper.insert(goods);
        //2.获取desc
        GoodsDesc goodsDesc = goodsEntity.getGoodsDesc();
        //2.1添加主键
        goodsDesc.setGoodsId(goods.getId());
        //2.2保存扩展信息
        goodsDescMapper.insert(goodsDesc);
        //3.保存sku
        this.saveItemList(goodsEntity);

    }
    //保存SKU信息
    private void saveItemList(GoodsEntity goodsEntity) {
        //3.获取item
        List<Item> itemList = goodsEntity.getItemList();
        if (goodsEntity.getGoods().getIsEnableSpec().equals("1")) {
            //开启了规格
            if (!CollectionUtils.isEmpty(itemList)) {
                for (Item item : itemList) {
                    //1.设置名字
                    String title = goodsEntity.getGoods().getGoodsName();
                    Map<String, String> map = JSON.parseObject(item.getSpec(), Map.class);
                    for (String key : map.keySet()) {
                        title += map.get(key) + " ";
                    }
                    //标题
                    item.setTitle(title);
                    //设置三级分类
                    //
                    item.setCategoryId(goodsEntity.getGoods().getCategory3Id());
                    item.setCreateTime(new Date());
                    item.setUpdateTime(new Date());
                    item.setGoodsId(goodsEntity.getGoods().getId());
                    item.setSellerId(goodsEntity.getGoods().getSellerId());
                    //查询分类对象
                    ItemCat itemCat = itemCatMapper.selectById(goodsEntity.getGoods().getCategory3Id());
                    item.setBrand(itemCat.getName());
                    //品牌
                    Brand brand = brandMapper.selectById(goodsEntity.getGoods().getBrandId());
                    item.setBrand(brand.getName());
                    //图片
                    List<Map> images = JSON.parseArray(goodsEntity.getGoodsDesc().getItemImages(), Map.class);
                    if (images.size() > 0) {
                        item.setImage((String) images.get(0).get("url"));
                    }
                    //保存
                    itemMapper.insert(item);
                }
            }
        } else {
            //不启用规格
            Item item = new Item();
            item.setTitle(goodsEntity.getGoods().getGoodsName());
            item.setPrice(goodsEntity.getGoods().getPrice());
            item.setNum(9999);
            item.setStatus("1");
            item.setIsDefault("1");
            item.setSpec("{}");
            itemMapper.insert(item);
        }
    }

    /**
     * 根据ID查询Goods
     *
     * @param id
     * @return
     */
    @Override
    public GoodsEntity findById(Long id) {
        //根据id查询SPU
        Goods goods = goodsMapper.selectById(id);
        //2.查询desc
        GoodsDesc goodsDesc = goodsDescMapper.selectById(id);
        //3.item
        QueryWrapper<Item> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id", id);
        List<Item> items = itemMapper.selectList(wrapper);
        //封装
        GoodsEntity entity = new GoodsEntity();
        entity.setGoods(goods);
        entity.setGoodsDesc(goodsDesc);
        entity.setItemList(items);
        return entity;
    }

    /**
     * 查询Goods全部数据
     *
     * @return
     */
    @Override
    public List<Goods> findAll() {
        return this.list(new QueryWrapper<Goods>());
    }

    /**
     * 审核
     * @param goodsId
     */
    @Override
    public void audit(Long goodsId) {
        //1.查询
        Goods goods = goodsMapper.selectById(goodsId);
        //2.是否删除
        if (goods.getIsDelete()!=null&&goods.getIsDelete().equals("1")) {
            throw new RuntimeException("商品已删除");
        }
        //上架和审核
        goods.setAuditStatus("1");
        goods.setIsMarketable("1");
        goodsMapper.updateById(goods);
    }

    /**
     * 上架
     * @param goodsId
     */
    @Override
    public void enableMarketable(Long goodsId) {
        //1.是否删除
        Goods goods = goodsMapper.selectById(goodsId);
        String isDelete = goods.getIsDelete();
        if (isDelete != null && isDelete.equals("1")) {
            throw new RuntimeException("商品已删除");
        }
        //2.是否审核通过
        if (goods.getAuditStatus().equals("0")) {
            throw new RuntimeException("商品未审核,请先审核");
        }
        //3.上架
        goods.setIsMarketable("1");
        goodsMapper.updateById(goods);
    }

    /**
     * 下架
     * @param goodsId
     */
    @Override
    public void disableMarketable(Long goodsId) {
        //1.是否删除
        Goods goods = goodsMapper.selectById(goodsId);
        String isDelete = goods.getIsDelete();
        if (isDelete != null && isDelete.equals("1")) {
            throw new RuntimeException("商品已删除");
        }
        //2.下架
        goods.setIsMarketable("0");
        goodsMapper.updateById(goods);
    }

    /**
     * 批量上架
     * @param goodsIds
     */
    @Override
    public void enableBatchMarketable(Long[] goodsIds) {
        if (goodsIds != null && goodsIds.length > 0) {
            List<Long> list = Arrays.asList(goodsIds);
            //查询所有商品
            List<Goods> goodsList = goodsMapper.selectBatchIds(list);
            for (Goods goods : goodsList) {
                //1.是否删除
                String isDelete = goods.getIsDelete();
                if (isDelete != null && isDelete.equals("1")) {
                    throw new RuntimeException("商品已删除");
                }
                //2.是否审核通过
                if (goods.getAuditStatus().equals("0")) {
                    throw new RuntimeException("商品未审核,请先审核");
                }
                //3.上架
                goods.setIsMarketable("1");
                goodsMapper.updateById(goods);
            }
        }
    }

    /**
     * 批量下架
     * @param goodsIds
     */
    @Override
    public void disableBatchMarketable(Long[] goodsIds) {
        if (goodsIds != null && goodsIds.length > 0) {
            List<Long> list = Arrays.asList(goodsIds);
            //查询所有商品
            List<Goods> goodsList = goodsMapper.selectBatchIds(list);
            for (Goods goods : goodsList) {
                String isDelete = goods.getIsDelete();
                if (isDelete != null && isDelete.equals("1")) {
                    throw new RuntimeException("商品已删除");
                }
                //2.下架
                goods.setIsMarketable("0");
                goodsMapper.updateById(goods);
            }
        }
    }
}
